function stackplot()
% basic template file for data analysis routines.
% gets the current datac window selection, and does the analysis
% for all selected record groups/blocks
% automatically refreshes the data arrays from the disk file if necessary
% and also shows how to generate a figure.
% 8/23/05 P. Manis

% the main routine is just a wrapper to handle the multiple selection and
% catch execution errors.
%
% Note: when testing, set the testflag to 1 so that we DO NOT do try/catch.
% you need to do this to catch the errors in the _go routine.
%
global CONTROL
sf = getmainselection; % read the list of selected traces
testflag = 1;
nsel = length(sf);
if(sf > 0)
    pflag = getplotflag; % read the plot flag (used in the routine template2)

    QueMessage('Stack plot routine', 1); % clear the que
    for i = 1:length(sf)
        if(testflag == 0)
            try
                template_go(sf(i), pflag, i, nsel);
            catch
                fprintf(1, 'Stack plot Failed execution for sf = %d\n  ***[File: %s, records: %d - %d ]\n', ...
                    sf(i), CONTROL(sf(i)).filename, CONTROL(sf(i)).recbeg, CONTROL(sf(i)).recend);
            end;
        else
            template_go(sf(i), 0, i, nsel); % also turn off plot flag when testing
        end;

    end;
    if(pflag) % plotflag and enable figure printing
        orient landscape % make the graph landscape on the paper.
        hf = findobj('tag', 'stackplot');
        if(~isempty(hf))
            print (hf, '-dps2');
        end;
    end;
end;



%--------------The real analysis routine------------------

function template_go(sf, pflag, index, nsel)

% access to all of the data and parameters
global DFILE ALLCH VOLTAGE CONTROL
persistent hmp hf nplot

% set some control parameters
isrc = 1;

% this next routine reads all of the data and information we need,
% including calculating some standard stuff that is put into DPAR.
% you will want DPAR.time especially - it is the time base that goes
% with the data.

[DFILE, DPAR, err] = ana_setup(DFILE, sf);
if(err ~= 0)
    return;
end;
isrc  = CONTROL(sf).basechan;

if(~isempty(ALLCH))
    VOLTAGE = ALLCH{isrc};
    CURRENT = ALLCH{isrc+1};
end;


% the analysis here is just finding spikes


% set up a figure window (or you could grab an existing one)
istack = (1/nsel)*ones(nsel, 1);
if(index == 1)
    nplot = ceil(sqrt(size(VOLTAGE, 1)));
    [hmp, hf] = multiplot('stackplot', nplot, nplot, istack);
set(hf, 'Tag', 'stackplot');
end;

figure(hf);
set(hf, 'Tag', 'stackplot');

for j = 1:size(VOLTAGE, 1)
    jax = j+nplot*nplot*(index-1);
    axes(hmp(jax));
    plot( DPAR.time(j,:), VOLTAGE(j,:));
    set(gca, 'Ylim', [-100 40]);
    if(j == 1)
        text(max(DPAR.time(j,:)), 40, sprintf('File: %s[%d]<%d>', DFILE.filename, DFILE.frec, isrc), ...
            'horizontalalignment', 'right', 'verticalalignment', 'top', 'fontsize', 8);
    end;
end;





